<script>
import {ArrowUpBold} from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  components: {
    ArrowUpBold
  },
  data() {
    return {
      // 反馈表单数据
      options: [
        {label: '漏洞/BUG', value: 'bug'},
        {label: '已有内容体验建议', value: 'existing'},
        {label: '新增内容建议', value: 'new'}
      ],
      selectedOption: 'bug',
      feedbackContent: '',

      // 查询表单
      queryForm: {
        pageNum: 1,
        pageSize: 10,
        order: null,
        adviceCategory: '',
        adviceStatus: '',
        adviceAuthor: '',
        adviceContent: ''
      },

      // 表格数据
      tableData: [],
      total: 0,
      loading: false,

      // 状态筛选选项
      statusOptions: [
        {label: '全部', value: ''},
        {label: '未优化', value: '未优化'},
        {label: '优化中', value: '优化中'},
        {label: '已优化', value: '已优化'},
        {label: '已删除', value: '已删除'},
        {label: '未处理/已读', value: '未处理/已读'},
      ],

      // 排序选项
      orderOptions: [
        {label: '默认排序', value: ''},
        {label: '创建时间升序', value: 1},
        {label: '创建时间降序', value: 2},
        {label: '更新时间升序', value: 3},
        {label: '更新时间降序', value: 4},
        {label: '点赞数升序', value: 5},
        {label: '点赞数降序', value: 6}
      ],

      // 详情对话框
      detailDialogVisible: false,
      currentAdvice: null,

      // 点赞状态缓存
      likeStatusMap: {},

      // 当前用户信息
      currentUser: null,

      // 状态更新对话框
      statusDialogVisible: false,
      statusForm: {
        id: null,
        status: '',
        adviceRemark: ''
      },
      isTogglingLike: false, // 防止点赞操作多次点击
    }
  },
  created() {
    this.initCurrentUser()
    this.fetchData()
    this.isAdmin()
  },
  computed: {
    ArrowUpBold() {
      return ArrowUpBold
    },
  },
  methods: {
    isAdmin() {
      return this.currentUser === 'admin'
    },
    // 初始化当前用户信息
    initCurrentUser() {
      this.currentUser = localStorage.getItem("id");
      if (!this.currentUser) {
        this.$message.warning('未获取到用户信息，部分功能可能受限')
      }
    },

    // 提交反馈
    submitFeedback() {


      if (!this.feedbackContent.trim()) {
        this.$message.warning('请输入您的反馈内容')
        return
      }

      if (!this.currentUser) {
        this.$message.warning('请先登录')
        return
      }

      const adviceDTO = {
        adviceCategory: this.selectedOption,
        adviceContent: this.feedbackContent,
        adviceAuthor: this.currentUser.username || '当前用户',
        userId: this.currentUser.id
      }

      axios.post('/advice/add', adviceDTO)
          .then(response => {
            if (response.data) {
              this.$message.success('感谢您的反馈！')
              this.feedbackContent = ''
              this.fetchData() // 刷新列表
            } else {
              this.$message.error(response.data.msg || '提交失败')
            }
          })
          .catch(error => {
            this.$message.error('提交失败: ' + error.message)
          })
    },

    // 获取建议列表
    async fetchData() {
      this.loading = true
      try {
        const response = await axios.get('/advice/page', {params: this.queryForm})
        if (response) {
          this.tableData = response.data.data.list || []
          this.total = response.data.data.total || 0
          this.preloadLikeStatus() // 重新加载点赞状态
        } else {
          this.$message.error(response.data.msg || '获取数据失败')
        }
      } catch (error) {
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },

    // 预加载点赞状态
    preloadLikeStatus() {
      if (!this.currentUser) return

      const promises = this.tableData.map(item => {
        return axios.get('/advice/checkLike', {
          params: {
            adviceId: item.adviceId,
            userId: this.currentUser
          }
        })
      })

      Promise.all(promises)
          .then(responses => {
            const newLikeStatusMap = {...this.likeStatusMap};
            responses.forEach((response, index) => {
              if (response.data && response.data.data !== undefined) {
                newLikeStatusMap[this.tableData[index].adviceId] = response.data.data > 0;
              }
            });
            this.likeStatusMap = newLikeStatusMap;
          })
          .catch(error => {
            console.error("加载点赞状态失败: ", error);
          });
    },

    // 分页事件处理
    handleSizeChange(newSize) {
      this.queryForm.pageSize = newSize
      this.fetchData()
    },

    handleCurrentChange(newPage) {
      this.queryForm.pageNum = newPage
      this.fetchData()
    },

    // 重置表单
    resetForm() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 10,
        order: null,
        adviceCategory: '',
        adviceStatus: '',
        adviceAuthor: '',
        adviceContent: ''
      }
      this.fetchData()
    },

    // 显示详情
    showDetail(row) {
      this.currentAdvice = row
      this.detailDialogVisible = true
    },

    // 点赞/取消点赞
    toggleLike(adviceId, event) {
      event.stopPropagation();

      if (!this.currentUser) {
        this.$message.warning("请先登录");
        return;
      }

      const hasLiked = this.likeStatusMap[adviceId];

      // 防止多次点击
      if (this.isTogglingLike) return;
      this.isTogglingLike = true;

      axios.put("/advice/likeChange/" + adviceId)
          .then((response) => {
            if (response.data) {
              // 更新点赞状态
              this.likeStatusMap[adviceId] = !hasLiked;

              // 更新点赞数
              const updatedTableData = this.tableData.map(item => {
                if (item.adviceId === adviceId) {
                  return {
                    ...item,
                    adviceLike: hasLiked ? item.adviceLike - 1 : item.adviceLike + 1
                  };
                }
                return item;
              });

              this.tableData = updatedTableData;

              this.$message.success(hasLiked ? "已取消点赞" : "点赞成功");
            } else {
              this.$message.error(response.data.msg || "操作失败");
            }
          })
          .catch((error) => {
            this.$message.error("操作失败: " + error.message);
          })
          .finally(() => {
            this.isTogglingLike = false;
          });
    },

    // 状态格式化
    formatStatus(status) {
      const statusMap = {
        '未优化': {icon: 'el-icon-warning', color: 'warning'},
        '优化中': {icon: 'el-icon-loading', color: 'primary'},
        '已优化': {icon: 'el-icon-success', color: 'success'},
        '已删除': {icon: 'el-icon-error', color: 'danger'},
        '未处理/已读': {icon: 'el-icon-warning', color: 'info'},
      }

      return statusMap[status] || {icon: 'el-icon-question', color: 'info'}
    },

    // 打开状态更新对话框
    openStatusDialog(row) {
      this.statusForm = {
        id: row.adviceId,
        status: row.adviceStatus,
        adviceRemark: row.adviceRemark || ''
      }
      this.statusDialogVisible = true
    },

    // 提交状态更新
    submitStatusUpdate() {
      if (!this.statusForm.status) {
        this.$message.warning('请选择状态')
        return
      }

      axios.put('/advice/status/' + this.statusForm.id, null, {
        params: {
          status: this.statusForm.status,
          adviceRemark: this.statusForm.adviceRemark
        }
      })
          .then(response => {
            if (response.data) {
              this.$message.success('状态更新成功')
              this.statusDialogVisible = false
              this.fetchData() // 刷新列表
            } else {
              this.$message.error(response.data.msg || '状态更新失败')
            }
          })
          .catch(error => {
            this.$message.error('状态更新失败: ' + error.message)
          })
    }
  }
}
</script>

<template>
  <div>
    <div class="title-container">
      <h1 class="title" style="line-height: 30px;font-size: 30px;text-align: left">意见反馈</h1>
      <p style="line-height: 22px;text-align: left">
        请选择你想要反馈的内容，然后填写你的建议。我们会尽快处理你的反馈
        <br>下方也可以查看别人发的意见反馈，也可以进行点赞
      </p>
    </div>
    <div class="feedback-container">
      <!-- 反馈表单部分 -->

      <div class="feedback-form">
        <div class="feedback-buttons" style="line-height: 15px">
          请选择建议类型
          <el-radio-group v-model="selectedOption">
            <el-radio-button
                v-for="option in options"
                :key="option.value"
                :value="option.value"
            >
              {{ option.label }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <el-input
            v-model="feedbackContent"
            :maxlength="1000"
            :rows="10"
            placeholder="请尽量详细地描述一下体验的时候遇到的问题，以及写出你想要的改进后的效果，你的每一条建议对我们都非常重要！"
            resize="vertical"
            show-word-limit
            type="textarea"
        ></el-input>

        <el-button type="primary" @click="submitFeedback">提交</el-button>
      </div>

      <!-- 查询表单 -->
      <el-form ref="queryForm" :model="queryForm" class="query-form" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="建议分类">
              <el-select v-model="queryForm.adviceCategory" placeholder="请选择分类">
                <el-option
                    v-for="option in options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-select v-model="queryForm.adviceStatus" placeholder="请选择状态">
                <el-option
                    v-for="option in statusOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="作者">
              <el-input v-model="queryForm.adviceAuthor" placeholder="请输入作者"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="内容">
              <el-input v-model="queryForm.adviceContent" placeholder="请输入内容关键词"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="排序方式">
              <el-select v-model="queryForm.order" placeholder="请选择排序方式">
                <el-option
                    v-for="option in orderOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="form-buttons">
            <el-button type="primary" @click="fetchData">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 建议表格部分 -->
      <el-table
          v-loading="loading"
          :cell-style="{ textAlign: 'center' }"
          :data="tableData"
          :header-cell-style="{ textAlign: 'center' }"
          style="width: 100%"
          @row-click="showDetail"
      >
        <el-table-column label="ID" prop="adviceId" width="80"/>
        <el-table-column label="分类" prop="adviceCategory" width="120">
          <template #default="{row}">
            {{
              options.find(opt => opt.value === row.adviceCategory)?.label || row.adviceCategory
            }}
          </template>
        </el-table-column>
        <el-table-column label="内容" prop="adviceContent" show-overflow-tooltip/>
        <el-table-column label="作者" prop="adviceAuthor" width="120"/>
        <el-table-column label="状态" prop="adviceStatus" width="120">
          <template #default="{row}">
            <el-tag :type="formatStatus(row.adviceStatus).color">
              <i :class="formatStatus(row.adviceStatus).icon"></i>
              {{ row.adviceStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 点赞列 -->
        <el-table-column label="点赞" width="120">
          <template #default="{row}">
            <el-button
                :style="{ color: likeStatusMap[row.adviceId] ? '#1890ff' : '#666' }"
                class="like-button"
                link
                @click="toggleLike(row.adviceId, $event)"
            >
              <el-icon>
                <ArrowUpBold/>
              </el-icon>
              <span>{{ row.adviceLike }}</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="adviceCreateTime" width="180"/>
        <el-table-column v-if="isAdmin()" label="操作" width="120">
          <template #default="{row}">
            <el-button type="text" @click.stop="openStatusDialog(row)">操作</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :total="total"
          class="pagination"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="建议详情" width="50%">
        <div v-if="currentAdvice">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="ID">{{ currentAdvice.adviceId }}</el-descriptions-item>
            <el-descriptions-item label="分类">
              {{
                options.find(opt => opt.value === currentAdvice.adviceCategory)?.label || currentAdvice.adviceCategory
              }}
            </el-descriptions-item>
            <el-descriptions-item label="内容">{{ currentAdvice.adviceContent }}</el-descriptions-item>
            <el-descriptions-item label="作者">{{ currentAdvice.adviceAuthor }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="formatStatus(currentAdvice.adviceStatus).color">
                <i :class="formatStatus(currentAdvice.adviceStatus).icon"></i>
                {{ currentAdvice.adviceStatus }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="点赞数">{{ currentAdvice.adviceLike }}</el-descriptions-item>
            <el-descriptions-item label="管理员备注">{{ currentAdvice.adviceRemark || '无' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentAdvice.adviceCreateTime }}</el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ currentAdvice.adviceUpdateTime }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>

      <!-- 状态更新对话框 -->
      <el-dialog v-model="statusDialogVisible" title="更新建议状态" width="30%">
        <el-form :model="statusForm" label-width="100px">
          <el-form-item label="状态" required>
            <el-select v-model="statusForm.status" placeholder="请选择状态">
              <el-option
                  v-for="option in statusOptions.filter(opt => opt.value)"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="管理员备注">
            <el-input
                v-model="statusForm.adviceRemark"
                :rows="4"
                placeholder="请输入备注信息"
                type="textarea"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitStatusUpdate">提交</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.feedback-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
}

.feedback-form {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #eaeaea;
  border-radius: 8px;
}

.el-radio-group {
  margin-bottom: 15px;
}

.el-button {
  display: block;
  margin: 15px auto;
}

.query-form {
  margin-bottom: 20px;
}

.form-buttons {
  display: flex;
  justify-content: flex-end;
  padding-top: 5px;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.el-table {
  cursor: pointer;
}

.like-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.feedback-buttons {
  margin-bottom: 15px;
  padding: 0; /* 减小内边距 */
}
</style>